﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using TdxHq.Invoker;
using log4net;

namespace TdxHq.Connect
{
    class ConnectPool
    {
        private static readonly ILog Log = LogManager.GetLogger("ConnectPool");
        
        public readonly List<TdxConnection> Connections = new List<TdxConnection>();

        public static readonly ConnectPool Instance = new ConnectPool();

        private ConnectPool()
        {
            List<TdxConnection> connections = new List<TdxConnection>();
            StringBuilder result = new StringBuilder(1024 * 1024);
            StringBuilder errInfo = new StringBuilder(256);

            Dictionary<string, DllInvoker> invokers = DllManager.Instance.Invokers;
            foreach (var pair in invokers)
            {
                var key = pair.Key;
                var c = new char[1] {'_'};
                var ip = key.Split(c)[0];
                result.Clear();
                errInfo.Clear();
                DllInvoker dllInvoker = pair.Value;
                int port;
                bool tryGetValue = Config.IpList.TryGetValue(ip, out port);
                bool success = tryGetValue;

                if (!success)
                {
                    continue;
                }

                QuoteDelegate.TdxHq_Connect connectDelegate =
                    (QuoteDelegate.TdxHq_Connect)
                    dllInvoker.Invoke("TdxHq_Connect", typeof(QuoteDelegate.TdxHq_Connect));
                long firstTicks = System.DateTime.Now.Ticks;
                bool connected = connectDelegate(ip, port, result, errInfo);
                long secondTicks = System.DateTime.Now.Ticks;
                long delay = secondTicks - firstTicks;
                string connectionName = "";

                Log.Info("ip:" + ip);
                Log.Info("result:" + result);
                Log.Info("delay:" + delay / 10000 + "ms");

                if (!connected)
                {
                    Log.Error("errInfo:" + errInfo);
                    Log.Error("放弃连接服务器:" + ip);
                    Log.Error("======================");
                    continue;
                }
                
                var strings = result.ToString().Split(new char[] {'\t'})[2].Split(new char[] {'\n'});
                connectionName = strings[1];
                
                Log.Error("======================");

                TdxConnection tdxConnection = new TdxConnection(ip, port, pair.Value)
                {
                    ConnectionName = connectionName,
                    Connected = true,
                    Delay = delay
                };
                connections.Add(tdxConnection);
            }

            Connections.AddRange(connections);
        }

        public TdxConnection GetFasterConncetion()
        {
            return Connections.Where(m => m.Connected).OrderBy(m => m.Delay).First();
        }

        public List<TdxConnection> GetAvailabeConncetion()
        {
            return Connections.Where(m => m.Connected).ToList();
        }
    }
}